package com.xiaode.controller.app.chat;

import cn.hutool.json.JSONUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Redis;
import com.xiaode.common.constant.Const;
import com.xiaode.common.model.*;
import com.xiaode.exce.EnumError;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class MailListService {
    public Ret findMailList() throws Exception {
        Kv kv = Kv.create();
        OrgGrade rootNode = OrgGrade.dao.findFirst("SELECT * FROM org_grade WHERE isRoot = 1");
        if (rootNode == null) {
            return Ret.ok("rootNode", rootNode);
        }
        rootNode.put("type", 1);
        List<Admin> orgAdmins = Admin.dao.find("SELECT ad.id,ad.name,ad.avatarUrl,ad.roleIds,ad.accountId,ad.user_type userType  FROM org_admin oa INNER JOIN admin ad ON oa.adminId = ad.id AND ad.user_type = 1 WHERE stratum = 1 AND ad.isDele = 0 ORDER BY CONVERT(ad.name USING GBK)");
        rootNode.put("admins", orgAdmins);
        rootNode.put("tableId", "1:" + rootNode.getId());
        //查询年级
        List<OrgGrade> orgGrades = OrgGrade.dao.find("SELECT id,name FROM org_grade WHERE isRoot = 0");
        //根据
        for (OrgGrade orgGrade : orgGrades) {
            orgGrade.put("type", 2);
            List<Admin> adminList = Admin.dao.find("SELECT ad.id,ad.name,ad.avatarUrl,ad.roleIds,ad.accountId,ad.user_type userType FROM org_admin oa INNER JOIN admin ad ON oa.adminId = ad.id AND ad.user_type = 1 WHERE stratum = 2 AND stratumId = ? AND ad.isDele = 0 ORDER BY CONVERT(ad.name USING GBK)", orgGrade.getId());
            orgGrade.put("admins", adminList);
            orgGrade.put("tableId", "2:" + orgGrade.getId());
            //查询该年级教师
            List<Record> recordList = Db.find("SELECT ad.id,ad.name,ad.avatarUrl,ad.roleIds,ad.accountId,oc.id classId,oc.name className,ad.user_type userType FROM org_admin oa INNER JOIN org_class oc ON oc.id = oa.stratumId AND oa.stratum = 3 INNER JOIN admin ad ON ad.id = oa.adminId AND ad.user_type = 1 WHERE oc.adminGradeId = ? AND ad.isDele = 0 ORDER BY CONVERT(ad.name USING GBK) ", orgGrade.getId());
            HashMap<Integer, List<Record>> recordHashMap = new HashMap<>();
            recordList.stream().forEach(record -> {
                List<Record> recordList1 = recordHashMap.get(record.getInt("classId"));
                if (recordList1 == null) {
                    ArrayList<Record> records = new ArrayList<>();
                    records.add(record);
                    recordHashMap.put(record.getInt("classId"), records);
                } else {
                    recordList1.add(record);
                }
            });

            //查询学生
            List<OrgClass> orgClasses = OrgClass.dao.find("SELECT id,name FROM org_class WHERE adminGradeId = ?", orgGrade.getId());
            if (orgClasses.size() > 0) {
                HashMap<Integer, List<Student>> hashMap = new HashMap<>(orgClasses.size());
                for (OrgClass orgClass : orgClasses) {
                    orgClass.put("admins", recordHashMap.get(orgClass.getId()));
                    ArrayList<Student> students = new ArrayList<>();
                    orgClass.put("students", students);
                    hashMap.put(orgClass.getId(), students);
                    orgClass.put("type", 3);
                }
                List<Integer> collect = orgClasses.stream().map(orgClass -> orgClass.getId()).collect(Collectors.toList());
                if (collect.size() > 0) {
                    kv.set("classIds", collect);
                    List<Student> students = Student.dao.template("findStudentByClassIds", kv).find();
                    for (Student student : students) {
                        List<Student> studentList = hashMap.get(student.getClasId());
                        studentList.add(student);
                    }
                }
            }
            orgGrade.put("children", orgClasses);
        }
        rootNode.put("children", orgGrades);
        return Ret.ok("node", rootNode);
    }

    /**
     * 我的群组
     */
	public Ret myChatGroup(Integer accountId) throws Exception {
        List<Record> records = Db.find("SELECT cg.*,cgu.level FROM chat_group_user cgu INNER JOIN chat_group cg ON cg.id = cgu.chatGroupId WHERE cgu.accountId = ?", accountId);        
        ArrayList<Record> runChatGroup = new ArrayList<>();
        records.stream().forEach(record -> {
            Integer level = record.getInt("level");
            if (level != 1) {
                runChatGroup.add(record);
            }
        });
        return Ret.ok("chatGroupUsers", records).set("runChatGroup", runChatGroup);
    }

    /**
     * 添加星标联系人
     */
    public Ret addStarFriends(Integer accountId, String accountIds) throws Exception {
        //查询当前星标联系人是否存在
        List<Integer> conntionAccountIdList = Db.query("SELECT conntionAccountId FROM star_connection WHERE accountId = ?", accountId);
        //要添加的账号
        List<Integer> addConntionAccountIdList = JSONUtil.toList(accountIds, Integer.class);
        //要入库的对象
        ArrayList<StarConnection> addStarConnectionList = new ArrayList<StarConnection>();
        
        for (Integer addConntionAccountId : addConntionAccountIdList) {
        	if (!conntionAccountIdList.contains(addConntionAccountId)) {
        		StarConnection starConnection = new StarConnection();
                starConnection.setAccountId(accountId);
                starConnection.setConntionAccountId(addConntionAccountId);
                addStarConnectionList.add(starConnection);
        	}
        }
        Db.batchSave(addStarConnectionList, addStarConnectionList.size());
        return Ret.ok();
        
    }

    /**
     * 删除星标联系人
     */
    public Ret delStarFriends(Integer accountIdMy, String accountIds) throws Exception {
    	List<Integer> accountIdList = JSONUtil.toList(accountIds, Integer.class);
    	if (accountIdList.size() == 0) {
    		return Ret.fail().set("error", EnumError.STAR_NOT_SELECT.getObj());
    	}
    	Db.template("deleteStarConnections", Kv.of("accountId", accountIdMy).set("conntionAccountIds", accountIdList)).delete();
        return Ret.ok();
    }

    /**
     * 查询星标联系人
     */
    public Ret findStarFriends(Integer accountIdMy) throws Exception {
    	List<Record> accountIdInfoList = new ArrayList<Record>();
    	List<Integer> conntionAccountIdList = Db.query("SELECT conntionAccountId FROM star_connection WHERE accountId = ?", accountIdMy);
    	for(Integer conntionAccountId : conntionAccountIdList) {
    		Record record = Redis.use().hget(Const.user.AccountIdInfo, conntionAccountId);
    		accountIdInfoList.add(record);
    	}
    	return Ret.ok("accountIdInfoList", accountIdInfoList);
    }


}
